<template>
    <div>
      <el-row>
        <h1>好友列表</h1>
        <el-button type="info" @click="centerDialogVisible = true" round style="margin-left:20px">添加好友</el-button>
      </el-row>
      <el-row>
        <card style="width:140px;margin-right:40px;margin-top: 20px;" v-for="friend in friends" :key="friend.id">
          <el-text class="mx-1">{{ friend.username }}</el-text>
          <div>
            <el-button type="primary" @click=invite(friend.username)>邀请</el-button>
          </div>
          
        </card>
      </el-row>

      <el-dialog title="添加好友" v-model="centerDialogVisible" width="30%" center>
      <div class="dialog2">
        <div class="start">
          <el-row>
            <span>搜索</span>
            <el-input
                v-model="input"
                class="input"
                placeholder="请输入好友用户名"
                @keyup.enter.native="addFriend"
                :suffix-icon="Calendar"
            />
            <el-button type="primary" icon="el-icon-search" @click=addFriend>添加好友</el-button>
          </el-row>
          
        </div>
        <span slot="footer" class="dialog-footer">
      </span>
      </div>
    </el-dialog>
      
    </div>
  </template>
   
  <script>
  import Qs from 'qs'
  export default {
    name: 'FriendList',
    inject: ['eventBus'],
    data() {
      return {
        input:"",
        centerDialogVisible:false,
        friends: [],
      };
    },
    created() {
      this.getFriend();
    },
    methods: {
      getFriend(){
        this.$axios.get('/friends',{params:{
          username:localStorage.getItem('name'),
        }
        })
        .then((response)=> {
            this.friends = response.data;
          })
        .catch(function (error) {
            console.log(error)
          })
      },
      addFriend(){
        let params = {
          username:localStorage.getItem('name'),
          friend:this.input
        };
        this.$axios.post(
          '/addFriends',Qs.stringify(params)
          ).then((response)=> {
            if(response.data==true){
              alert("添加成功")
            //   _this.$message({
            //   message: '恭喜你，注册成功',
            //   type: 'success'
            // })
            this.centerDialogVisible = false
            this.getFriend()
            }
            else {
              alert('该用户不存在')
            }
          })
      },
      invite(name){
        this.$emit('message-updated', name);
      }
    },
  };
  </script>

<style scoped>
.input{
  width:50%;
  margin-right:5%;
  margin-left:5%;
  margin-bottom: 10%;
}
</style>